package com.ruoyi.system.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.phprpc.util.AssocArray;
import org.phprpc.util.PHPSerializer;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;


@Slf4j
public class JsonToPhp {


    public static String jsonToPhp(String jsonData) {
        List<Map<String, String>> list = JSON.parseObject(jsonData, new TypeReference<List<Map<String, String>>>() {
        });

        PHPSerializer phpSerializer = new PHPSerializer();
        AssocArray array = new AssocArray();

        for (int i = 0; i < list.size(); i++) {
            Map<String, String> item = list.get(i);
            AssocArray itemArray = new AssocArray();

            for (Map.Entry<String, String> entry : item.entrySet()) {
                itemArray.set(entry.getKey(), entry.getValue());
            }
            array.set(i, itemArray);
        }

        byte[] serializedData = new byte[0];
        try {
            serializedData = phpSerializer.serialize(array);
        } catch (Exception e) {
            log.info("jsonToPhp报错:{}", e.getMessage());
        }
        String phpStr = new String(serializedData, StandardCharsets.UTF_8);
        log.info("jsonToPhp 传入数据是:{}", phpStr);
        return phpStr;
    }


    public static String jsonStrToPhpHead(String json) {
        if (StringUtils.isEmpty(json)) {
            return "";
        }
        int byteLength = json.getBytes(StandardCharsets.UTF_8).length;
        return "s:" + byteLength + ":\"" + json + "\";";
    }


    public static String phpHeadStrToJson(String phpSerializedStr) {
        if (StringUtils.isEmpty(phpSerializedStr)) {
            return "";
        }
        try {
            int startQuote = phpSerializedStr.indexOf(":\"") + 2;
            int endQuote = phpSerializedStr.lastIndexOf("\"");
            if (startQuote >= 0 && endQuote > startQuote) {
                String jsonStr = phpSerializedStr.substring(startQuote, endQuote);
                return jsonStr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}